package org.ticlib.taskwrapper
{
	import flash.events.Event;
	
	import mx.rpc.AbstractOperation;
	import mx.rpc.events.FaultEvent;
	
	import org.ticlib.task.ServiceInvoker;
	import org.ticlib.task.Task;

	public class ServiceWrapper extends TaskWrapper
	{
		public static function add(operation:AbstractOperation, args:Array=null, id:String=""):TaskWrapper
		{
			var obj:ServiceWrapper = new ServiceWrapper(operation, args, id);
			return obj;
		}

		public function ServiceWrapper(operation:AbstractOperation, args:Array, id:String="")
		{
			super(id);
			task = new ServiceInvoker();
			task.addEventListener(Event.COMPLETE, onComplete);
			task.addEventListener(FaultEvent.FAULT, onFault);
			task.addEventListener(Event.CANCEL, onCancel);
			task.addEventListener(Event.CONNECT, onConnect);

			(task as ServiceInvoker).operation = operation;
			(task as ServiceInvoker).arguments = args;
		}

		private function onComplete(e:Event):void
		{
			resultFunction.call(this, (e.target as Task).resultObject, uniqueId);
		}
		
		private function onFault(e:Event):void
		{
			faultFunction.call(this, (e.target as Task).faultObject, uniqueId);
		}
		
		private function onCancel(e:Event):void
		{
			cancelFunction.call(this, (e.target as Task).resultObject, uniqueId);
		}
		
		private function onConnect(e:Event):void
		{
			connectFunction.call(this, (e.target as Task).resultObject, uniqueId);
		}
		
		override public function result(resultFunction:Function):TaskWrapper 
		{
			this.resultFunction = resultFunction;
			return this;
		}
		override public function cancel(cancelFunction:Function):TaskWrapper
		{
			this.cancelFunction = cancelFunction;
			return this;
		}
		
		override public function fault(faultFunction:Function):TaskWrapper
		{
			this.faultFunction = faultFunction;
			return this;
		}
		
		override public function connect(connectFunction:Function):TaskWrapper
		{
			this.connectFunction = connectFunction;
			return this;
		}
		
		override public function add(wrapper:TaskWrapper):TaskWrapper
		{
			return this;
		}
		
		override public function execute():void
		{
			task.execute();
		}		
	}
}